<template>
  <div class="login">
    <el-form :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">征兵通</h3>
      <!-- 账号输入框 -->
      <el-form-item prop="username">
        <el-input class="custom-input" v-model="loginForm.username" type="text" size="large" autocomplete="off"
          placeholder="账号">
          <template #prefix>
            <img :src="userIcon" alt="用户名" class="custom-prefix-icon" />
          </template>
        </el-input>
      </el-form-item>
      <!-- 密码输入框 -->
      <el-form-item prop="password">
        <el-input class="custom-input" v-model="loginForm.password" type="password" size="large" autocomplete="off"
          placeholder="密码">
          <template #prefix>
            <img :src="passwordIcon" alt="密码" class="custom-prefix-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="code-container">
          <el-input v-model="loginForm.code" size="large" autocomplete="off" placeholder="验证码" style="width: 63%"
            @keyup.enter="handleLogin">
            <template #prefix>
              <img :src="codeIcon" alt="验证码图标" class="custom-prefix-icon" />
            </template>
          </el-input>
          <div class="login-code" style="margin-left: 10px;">
            <img :src="codeImg" @click="getCode" class="login-code-img" />
          </div>
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button style="width:100%;" type="primary" @click="handleLogin">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="app-footer">
    <AppFooter />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import axios from 'axios';
import Cookies from 'js-cookie';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import codeIcon from "@/assets/icons/code.svg";
import userIcon from "@/assets/icons/user.svg";
import passwordIcon from "@/assets/icons/password.svg";
import useUserStore from '@/store/modules/user'
import { connectWebSocket } from '@/services/WebSocketService';
import AppFooter from '@/components/AppFooter.vue';
import { getCodeImg, getInfo } from '@/api/login';
import { getToken } from '@/utils/auth';


let codeImg = ref('')
const loginForm = ref({
  username: "13984123707",
  password: "Ab@123456!",
  code: "",
})

const router = useRouter()
// 获取当前组件实例的代理对象
const { proxy } = getCurrentInstance();
const userStore = useUserStore()



// 表单验证规则
// blur：当输入框失去焦点时触发验证（如用户点击其他位置）。
// change：当输入内容发生变化时立即触发验证。
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
};


onMounted(() => {
  getCode();
})


// 获取登录验证码
function getCode() {
  getCodeImg().then(response => {
    // 创建临时对象URL（注意这里要用response.data）
    const blob = new Blob([response.data], { type: 'image/png' })
    codeImg.value = URL.createObjectURL(blob)

    // 调试用：检查生成的URL
    console.log('生成的验证码URL:', codeImg.value)
  }).catch(error => {
    console.error('验证码获取失败:', error)
    ElMessage.error('验证码加载失败')
  })
}

function handleLogin() {
  userStore.login(loginForm.value).then(() => {
    router.push("/index")
    ElMessage({
      message: '登录成功',
      type: 'success',
    });
    // 登录成功后连接 WebSocket
    connectWebSocket();
    addUserInfo();
    router.push("/index")

  }).catch(() => {
    loading.value = false;
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode();
    }
  });

}


// 工具函数：检查 userId 是否过期
function checkUserIdExpiry() {
  const userId = localStorage.getItem('userId');
  const exp = localStorage.getItem('userId_exp');

  if (userId && exp) {
    const now = Date.now();
    if (now > parseInt(exp)) {
      localStorage.removeItem('userId');
      localStorage.removeItem('userId_exp');
      console.log('用户ID已过期');
      return null;
    }
  }
  return userId;
}
/**
 * 解析 JWT Token 并提取用户信息
 * @param {string} token - JWT令牌字符串
 * @returns {Object} 包含用户信息的对象
 */
function parseJwtToken(token) {
  try {
    // 分割JWT的三部分
    const [header, payload, signature] = token.split('.');

    // Base64解码并解析payload
    const decodedPayload = JSON.parse(
      atob(
        payload.replace(/-/g, '+').replace(/_/g, '/') // 处理URL安全Base64
        + '=='.substring(0, (3 * payload.length) % 4) // 补齐Base64填充
      )
    );

    // 提取目标字段
    const requiredClaims = ['userId', 'avatarUrl', 'username', 'roleId'];
    const result = {};

    requiredClaims.forEach(claim => {
      if (typeof decodedPayload[claim] !== 'undefined') {
        result[claim] = decodedPayload[claim];
      } else {
        console.warn(`JWT 缺少必需字段: ${claim}`);
        result[claim] = null; // 设置默认值
      }
    });

    return result;
  } catch (error) {
    console.error('JWT 解析失败:', error);
    return {
      userId: null,
      avatarUrl: null,
      username: null
    };
  }
}

// 将用户相关信息存储到浏览器中的localStorage中
function addUserInfo() {
  const claims = parseJwtToken(getToken());
  if (claims.userId) {
    // 安全存储方案
    try {
      localStorage.setItem('userInfo', JSON.stringify({
        userId: claims.userId,
        avatarUrl: claims.avatarUrl,
        username: claims.username,
        roleId: claims.roleId,
        timestamp: Date.now() // 添加时间戳用于验证数据时效
      }));

      console.log('用户信息已存储');
      return true;
    } catch (e) {
      console.error('localStorage 存储失败:', e);
      // 处理存储空间不足的情况
      if (e.name === 'QuotaExceededError') {
        localStorage.clear();
        return storeUserClaims(token);
      }
      return false;
    }
  }
  return false;

}

// 获取登录用户的角色信息
function getRoleInfo(userId) {
  axios({
    url: "/api/admin/getRoleInfo",
    method: "GET",
    params: {
      id: userId
    }
  }).then(result => {
    console.log(result);
    const roleId = result.data.data.roleId
    localStorage.setItem('roleId', roleId);
  })
}

// 获取登录用户详细信息
function getUserInfo() {
  getInfo()
}

</script>

<style scoped lang='scss'>
.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  /* 加载背景图片 */
  background-image: url('@/assets/login.jpg');
  /* 让背景图基于容器大小伸缩 */
  background-size: cover;
  /* 背景图垂直、水平均居中 */
  background-position: center center;
  /* 背景图不平铺 */
  background-repeat: no-repeat;
  /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
  background-attachment: fixed;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 350px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }
}


.custom-input .el-input__prefix>svg {
  width: 18px !important;
  /* 覆盖默认样式 */
  height: 18px !important;
  /* 覆盖默认样式 */
  margin-right: 5px;
  /* 图标与文本的间距 */
}


.code-container {
  display: flex;
  align-items: center;
  /* 垂直居中 */
}

.login-code {
  margin-left: 10px;
  /* 输入框与验证码图片的间距 */
}

/* 验证码图片样式（确保与输入框对齐） */
.login-code-img {
  cursor: pointer;
  height: 40px;
  /* 根据输入框高度调整 */
}

/* 前缀图标样式（如验证码图标） */
.custom-prefix-icon {
  width: 18px;
  height: 18px;
  margin-right: 5px;
}

.app-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 9999; // 确保覆盖层级高于登录容器
  background: rgba(42, 42, 52, 0.9); // 可选：添加背景色增强可见性
  padding: 10px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1); // 可选：添加阴影效果
}
</style>